<template>
	<el-drawer v-model="isShowDrawer" direction="rtl" :before-close="handleClose" :size="curDrawerSize" :close-on-click-modal="isReadOnly">
		<template #header="{ titleId, titleClass }">
			<div class="zs-drawer-header" :id="titleId" :class="titleClass">
				<i class="icon-b-item zs-icon zs-text-blue zs-space-right-sm"></i>
				<div class="zs-title zs-text-black">设施详情</div>
			</div>
		</template>

		<template #default>
			<el-container class="zs-drawer-container">
				<el-scrollbar class="zs-drawer-content">
					<!-- card1 -->
					<div class="zs-align-center zs-space-bottom" id="sm-drawer-demo-card-01">
						<i class="icon-s-item zs-icon zs-text-blue zs-space-right-sm"></i>
						<div class="zs-title">预算清单</div>
					</div>
					<div class="zs-card zs-space-bottom">
						<el-form ref="form1" label-position="right" label-width="100px" :rules="rules.rulesBill" :model="formData.data">
							<el-form-item label="一级分类：" prop="level1">
								<el-select v-model="formData.data.level1" class="zs-full-item" :placeholder="isReadOnly ? ' ' : '请选择'" :disabled="isReadOnly" filterable @change="getClassificationDownFn('second', 'action')">
									<el-option v-for="item in classificationDown.first" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</el-form-item>
							<el-form-item label="二级分类：" prop="level2">
								<el-select v-model="formData.data.level2" class="zs-full-item" :placeholder="isReadOnly ? ' ' : '请选择'" :disabled="isReadOnly" filterable @change="getClassificationDownFn('third', 'action')">
									<el-option v-for="item in classificationDown.second" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</el-form-item>
							<el-form-item label="三级分类：" prop="level3">
								<el-select v-model="formData.data.level3" class="zs-full-item" :placeholder="isReadOnly ? ' ' : '请选择'" :disabled="isReadOnly" filterable @change="getClassificationDownFn('inventoryList', 'action')">
									<el-option v-for="item in classificationDown.third" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</el-form-item>
							<el-form-item label="清单名称：" prop="inventoryId">
								<el-select v-model="formData.data.inventoryId" class="zs-full-item" :placeholder="isReadOnly ? ' ' : '请选择'" :disabled="isReadOnly" filterable>
									<el-option v-for="item in classificationDown.inventoryList" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</el-form-item>
						</el-form>
					</div>
					<!-- card2 -->
					<div class="zs-align-center zs-space-top-lg zs-space-bottom" id="sm-drawer-demo-card-02">
						<i class="icon-s-item zs-icon zs-text-blue zs-space-right-sm"></i>
						<div class="zs-title">设施信息</div>
					</div>
					<div class="zs-card zs-space-bottom">
						<el-form ref="form2" label-position="right" label-width="100px" :rules="rules.rulesEquipment" :model="formData.data">
							<el-form-item label="设施名称：" prop="facilityName">
								<el-input v-model="formData.data.facilityName" maxlength="50" clearable :disabled="isReadOnly" />
							</el-form-item>
							<el-form-item label="设施品牌：">
								<el-input v-model="formData.data.facilityBrand" maxlength="50" clearable :disabled="isReadOnly" />
							</el-form-item>
							<el-form-item label="设施规格：">
								<el-input v-model="formData.data.facilitySpecifications" maxlength="50" clearable :disabled="isReadOnly" />
							</el-form-item>
							<el-form-item label="设施编号：" prop="facilityNum">
								<el-input v-model="formData.data.facilityNum" :disabled="handleType == 'add' ? false : true" />
							</el-form-item>
							<el-form-item label="所在楼层：" prop="floorNum">
								<el-select v-model="formData.data.floorNum" class="zs-full-item" :placeholder="isReadOnly ? ' ' : '请选择'" :disabled="isReadOnly">
									<el-option v-for="item in dictObj.BUILDING_LEVEL" :key="item.id" :label="item.dictLabel" :value="item.dictValue" />
								</el-select>
							</el-form-item>
							<el-form-item label="设施位置：" prop="facilityLocation">
								<el-input v-model="formData.data.facilityLocation" maxlength="50" clearable :disabled="isReadOnly" />
							</el-form-item>
							<el-form-item label="说明：">
								<el-input v-model="formData.data.remark" :maxlength="curTextareaLength" show-word-limit type="textarea" :autosize="{ minRows: 2 }" :disabled="isReadOnly" />
							</el-form-item>
							<el-form-item label="设施附件：">
								<hsFileUpload :limit="10" :fileList="formData.data.accessoryList" :requestBaseUrl="baseUrl" :fileSize="1000" acceptType="*" :multiple="false" :disabled="isReadOnly" @handleRemove="handleRemove" @handleUpload="uploadLogoRequest"> </hsFileUpload>
							</el-form-item>
						</el-form>
					</div>
					<!-- card3 -->
					<div class="zs-align-center zs-space-top-lg zs-space-bottom" id="sm-drawer-demo-card-03">
						<i class="icon-s-item zs-icon zs-text-blue zs-space-right-sm"></i>
						<div class="zs-title">质保信息</div>
					</div>
					<div class="zs-card zs-space-bottom">
						<el-form ref="form3" label-position="right" label-width="100px" :rules="rules.rulesQuality" :model="formData.data">
							<el-form-item label="开始日期：" prop="warrantyStartTime">
								<el-date-picker v-model="formData.data.warrantyStartTime" type="datetime" style="width: 100%" :disabled="isReadOnly" value-format="x" />
							</el-form-item>
							<el-form-item label="结束日期：" prop="warrantyEndTime">
								<el-date-picker v-model="formData.data.warrantyEndTime" type="datetime" style="width: 100%" :disabled="isReadOnly" value-format="x" />
							</el-form-item>
							<el-form-item label="质保期：">
								<el-input v-model="formData.data.effectState" maxlength="50" clearable disabled placeholder=" " />
							</el-form-item>
						</el-form>
					</div>
					<!-- card4 -->
					<div class="zs-align-center zs-space-top-lg zs-space-bottom" id="sm-drawer-demo-card-04">
						<i class="icon-s-item zs-icon zs-text-blue zs-space-right-sm"></i>
						<div class="zs-title">寿命信息</div>
					</div>
					<div class="zs-card zs-space-bottom">
						<el-form ref="form4" label-position="right" label-width="100px" :rules="rules.rulesLife" :model="formData.data">
							<el-form-item label="开始日期：" prop="lifeStartTime">
								<el-date-picker v-model="formData.data.lifeStartTime" type="datetime" style="width: 100%" :disabled="isReadOnly" value-format="x" />
							</el-form-item>
							<el-form-item label="结束日期：" prop="lifeEndTime">
								<el-date-picker v-model="formData.data.lifeEndTime" type="datetime" style="width: 100%" :disabled="isReadOnly" value-format="x" />
							</el-form-item>
							<el-form-item label="寿命期：">
								<el-input v-model="formData.data.lifeEffectState" maxlength="50" clearable disabled placeholder=" " />
							</el-form-item>
						</el-form>
					</div>
					<!-- card5 -->
					<div class="zs-align-center zs-space-top-lg zs-space-bottom" id="sm-drawer-demo-card-05">
						<i class="icon-s-item zs-icon zs-text-blue zs-space-right-sm"></i>
						<div class="zs-title">设施状态</div>
					</div>
					<div class="zs-card zs-space-bottom">
						<el-form ref="form5" label-position="right" label-width="100px" :rules="rules.rulesStatus" :model="formData.data">
							<el-form-item label="设施状态：" prop="facilityStatusDict">
								<el-select v-model="formData.data.facilityStatusDict" class="zs-full-item" :placeholder="isReadOnly ? ' ' : '请选择'" :disabled="isReadOnly">
									<el-option v-for="item in dictObj.PROPERTY_DEVICE_STATUS" :key="item.id" :label="item.dictLabel" :value="item.id" />
								</el-select>
							</el-form-item>
						</el-form>
					</div>
					<!-- card6 -->
					<CreateUserInfo v-if="formData.data.id" ref="createDataRef" title="创建信息" id="sm-drawer-demo-card-06" />
				</el-scrollbar>
				<hsDocWrapper :nodeList="curNodeList" />
			</el-container>
		</template>

		<template v-if="handleType != 'info'" #footer>
			<div>
				<el-button class="zs-btn-md zs-btn-primary" @click="doConfirm">提交</el-button>
			</div>
		</template>
	</el-drawer>
</template>

<script setup>
	import CreateUserInfo from '@/components/createUserInfo.vue';
	import { getInventoryApi } from '@/api/common.js';
	import { facilityAddApi, facilityUpdateApi, facilityInfoApi } from '@/api/facility.js';
	import { ElMessage } from 'element-plus';
	import { ref, reactive, watch, nextTick } from 'vue';
	import { useStore } from 'vuex';
	import { useRoute } from 'vue-router';
	import { deepClone } from '@/utils/publicUtils';

	const route = useRoute();

	const props = defineProps({
		isShow: { type: Boolean, default: false },
		isReadOnly: { type: Boolean, default: true },
		handleType: { type: String, default: '' },
		currentRow: { type: Object },
	});

	let store = useStore();
	const curDrawerSize = ref(store.state.uiDrawerSize);
	const curTextareaLength = ref(store.state.uiTextareaLength);

	let dictObj = store.getters.getDictObj(['VALIDATE_FLAG', 'PROPERTY_DEVICE_STATUS', 'BUILDING_LEVEL']);

	let isShowDrawer = ref(props.isShow);

	const emit = defineEmits(['close']);

	const baseUrl = ref(process.env.VUE_APP_BASE_API_ZK);

	// 三级分类
	let classificationDown = reactive({
		first: [],
		second: [],
		third: [],
		inventoryList: [],
	});
	
	let formData = reactive({ data: { warrantyStartTime: '', warrantyEndTime: '', effectState:'', lifeStartTime: '', lifeEndTime: '', lifeEffectState: '', accessoryList: [] } });

	const rules = reactive({
		rulesBill: {
			level1: [{ required: true, message: '请选择一级分类', trigger: 'change' }],
			level2: [{ required: true, message: '请选择二级分类', trigger: 'change' }],
			level3: [{ required: true, message: '请选择三级分类', trigger: 'change' }],
			inventoryId: [{ required: true, message: '请选择清单名称', trigger: 'change' }],
		},
		rulesEquipment: {
			facilityName: [{ required: true, message: '请填写设施名称', trigger: ['blur', 'change'] }],
			facilityNum: [
				{ required: true, message: '请填写设施编号', trigger: ['blur', 'change'] },
				{ pattern: /^[a-zA-Z0-9_-]+$/, message: '输入支持大小写字母，数字，下划线，中横线' },
			],
			floorNum: [{ required: true, message: '请选择所在楼层', trigger: 'change' }],
			facilityLocation: [{ required: true, message: '请填写设施位置', trigger: ['blur', 'change'] }],
		},
		rulesQuality: {
			warrantyStartTime: [
				{ required: true, message: '请选择开始日期', trigger: ['blur', 'change'] },
				{ validator: endDateValid, trigger: ['blur', 'change'] },
			],
			warrantyEndTime: [
				{ required: true, message: '请选择结束日期', trigger: ['blur', 'change'] },
				{ validator: endDateValid, trigger: ['blur', 'change'] },
			],
		},
		rulesLife: {
			lifeStartTime: [
				{ required: true, message: '请选择开始日期', trigger: ['blur', 'change'] },
				{ validator: endDateValid, trigger: ['blur', 'change'] },
			],
			lifeEndTime: [
				{ required: true, message: '请选择结束日期', trigger: ['blur', 'change'] },
				{ validator: endDateValid, trigger: ['blur', 'change'] },
			],
		},
		rulesStatus: {
			facilityStatusDict: [{ required: true, message: '请选择设施状态', trigger: 'change' }],
		},
	});

	const curNodeList = ref([
		{ name: '预算清单', id: 'sm-drawer-demo-card-01' },
		{ name: '设施信息', id: 'sm-drawer-demo-card-02' },
		{ name: '质保信息', id: 'sm-drawer-demo-card-03' },
		{ name: '寿命信息', id: 'sm-drawer-demo-card-04' },
		{ name: '设施状态', id: 'sm-drawer-demo-card-05' },
	]);

	const form1 = ref();
	const form2 = ref();
	const form3 = ref();
	const form4 = ref();
	const form5 = ref();
	const createDataRef = ref();

	watch(
		() => props.isShow,
		(newVal, oldVal) => {
			isShowDrawer.value = newVal;
			nextTick(() => {
				newVal && props.handleType == 'add' && initForm();
				newVal && ['info', 'edit'].includes(props.handleType) && getInfo(props.currentRow?.id);
			});
		},
	);

	// 失效时间自定义校验 | 设置质保期
	function endDateValid(rule, value, callback) {
		let dataListQuality = ['warrantyStartTime', 'warrantyEndTime', 'effectState'];
		let dataListLife = ['lifeStartTime', 'lifeEndTime', 'lifeEffectState'];
		let target = dataListQuality.includes(rule.field) ? dataListQuality : dataListLife
		let diffVal = (formData.data[target[1]] || 0) - (formData.data[target[0]] || 0);
		if (formData.data[target[0]] && formData.data[target[1]]) {
			if (diffVal < 0) {
				formData.data[target[2]] = '';
				callback(new Error('结束日期不能小于开始日期'));
			} else {
				let form = dataListQuality.includes(rule.field) ? form3 : form4;
				form.value.clearValidate(target[0]);
				diffDate(formData.data[target[0]], formData.data[target[1]], target[2]);
				callback();
			}
		}
	}

	// 设置有效期
	const diffDate = (startDate, endDate, targetFiled) => {
		let nowTime = new Date().getTime();
		if (startDate <= nowTime && nowTime <= endDate) {
			formData.data[targetFiled] = targetFiled == 'effectState' ? '质保期内' : '寿命期内';
		} else {
			formData.data[targetFiled] = targetFiled == 'effectState' ? '质保期外' : '寿命期外';
		}
	};

	//三级分类 | 清单名称
	const getClassificationDownFn = async (type = 'first', action) => {
		let params = {};
		if (type == 'second' && action == 'action') {
			initAffectFiled('level2', 'second');
			initAffectFiled('level3', 'third');
			initAffectFiled('inventoryId', 'inventoryList');
		} else if (type == 'third' && action == 'action') {
			initAffectFiled('level3', 'third');
			initAffectFiled('inventoryId', 'inventoryList');
		} else if (type == 'inventoryList' && action == 'action') {
			initAffectFiled('inventoryId', 'inventoryList');
		}
		setTimeout(function () {
			action == 'action' && clearClassValidate();
		}, 30);

		params.classify1 = ['inventoryList', 'third', 'second'].includes(type) ? formData.data.level1 : '';
		params.classify2 = ['inventoryList', 'third'].includes(type) ? formData.data.level2 : '';
		params.classify3 = ['inventoryList'].includes(type) ? formData.data.level3 : '';

		let res = await getInventoryApi(params);
		let resData = res.data;
		if (resData.code == 200) {
			classificationDown[type] = resData.data;
		}
	};

	//级联选择变化时清空下选的被动项
	const initAffectFiled = (fieldName, listName) => {
		formData.data[fieldName] = '';
		classificationDown[listName] = [];
	};
	const clearClassValidate = () => {
		form1.value.clearValidate('level2');
		form1.value.clearValidate('level3');
		form1.value.clearValidate('inventoryId');
	};

	//详情
	const getInfo = async id => {
		let res = await facilityInfoApi(id);
		if (res.data.code !== 200) return;
		let existCreate = curNodeList.value.find(item => item.id === 'sm-drawer-demo-card-06');
		!existCreate && curNodeList.value.push({ name: '创建信息', id: 'sm-drawer-demo-card-06' });
		let cData = Object.assign(res.data.data);
		handleDataType(cData);
		formData.data = cData;
		form3.value.clearValidate();
		form4.value.clearValidate();

		//有效期
		diffDate(formData.data.warrantyStartTime, formData.data.warrantyEndTime, 'effectState');
		diffDate(formData.data.lifeStartTime, formData.data.lifeEndTime, 'lifeEffectState');
		//分类数据源
		getClassificationDownFn('second');
		getClassificationDownFn('third');
		getClassificationDownFn('inventoryList');
		nextTick(() => {
			createDataRef.value.setData(formData.data);
		});
	};

	const handleDataType = data => {
		data.facilityStatusDict = String(data.facilityStatusDict);
		data.level1 = Number(data.level1);
		data.level2 = Number(data.level2);
		data.level3 = Number(data.level3);
		if (data.accessoryList) {
			data.accessoryList.forEach(item => {
				item.url = item.absolutePath;
				item.name = item.attachmentName;
			});
		} else {
			data.accessoryList = [];
		}
	};

	//提交
	const doConfirm = () => {
		const forms = [form1, form2, form3, form4, form5];
		const validatePromises = forms.map(form => new Promise(resolve => form.value.validate(resolve)));
		Promise.all(validatePromises).then(async results => {
			const isValid = results.every(valid => valid);
			if (isValid) {
				formData.data.projectCode = route.query.projectCode;
				formData.data.inventoryName = classificationDown.inventoryList.find(item => item.id == formData.data.inventoryId)?.name;
				let res = formData.data.id ? await facilityUpdateApi(formData.data) : await facilityAddApi(formData.data);
				if (res.data.code !== 200) return;
				ElMessage({
					message: '提交成功',
					type: 'success',
				});
				isShowDrawer.value = false;
				emit('close', { isShow: false, isRefresh: true });
			}
		});
	};

	//关闭抽屉
	const handleClose = done => {
		emit('close', { isShow: false });
		done();
	};

	// 上传图片成功后的回调
	function uploadLogoRequest(res, index) {
		let file = deepClone(res);
		file.attachmentName = file.originalName;
		file.attachmentUrl = file.relativePath;
		formData.data.accessoryList.push(file);
		form2.value.clearValidate('accessoryList');
	}

	// 删除图片成功后的回调
	function handleRemove(res) {
		let targetId = res.id || res.response.data.res.id;
		let index = formData.data.accessoryList.findIndex(item => item.id == targetId);
		index > -1 && formData.data.accessoryList.splice(index, 1);
		form2.value.clearValidate('accessoryList');
	}

	//初始化
	const initForm = () => {
		formData.data = { accessoryList: [] };
		const forms = [form1, form2, form5];
		forms.forEach(form => {
			form.value.resetFields();
		});
		initTime()
		let existCreate = curNodeList.value.find(item => item.id === 'sm-drawer-demo-card-06');
		existCreate && curNodeList.value.pop();
	};


	//初始化时间
	function initTime() {
		formData.data.warrantyStartTime = new Date(new Date().toLocaleDateString()).getTime()
		formData.data.warrantyEndTime = new Date('2100-12-31 23:59:59').getTime()
		formData.data.lifeStartTime = new Date(new Date().toLocaleDateString()).getTime()
		formData.data.lifeEndTime = new Date('2100-12-31 23:59:59').getTime()
		diffDate(formData.data.warrantyStartTime,formData.data.warrantyEndTime,'effectState');
		diffDate(formData.data.lifeStartTime,formData.data.lifeEndTime,'lifeEffectState');
		form3.value.clearValidate()
		form4.value.clearValidate()
	}

	getClassificationDownFn('first', '');
</script>
